/**
 * Created by macos on 14-10-16.
 */

(function(){
  var UserServicesController = {};
  var root = this;

  function findOneUserService(next) {

    UserServices.findOne({userId:request.userId})
      .exec(function(error, result){
        if (error) {
          next(error);
        } else {
          next(null, result);
        }
      });
  }

  function createUserService(userServices, next) {

    var service = request.service;
    if (!_.has(userServices,'id')) {

      request.services = service;
      UserServices.create(request)
        .exec(function(error, result){
          if (error) {
            next(error);
          } else {
            next(null, result, service);
          }
        });
    } else {
      next(null, userServices, service);
    }
  }

  function updateUserService(userServices, service, next) {

    var services = userServices.services;
    if(!_.contains(services, service)) {
      services.push(service);

      request.services = services;
      UserServices.update({id:userServices.id}, request)
        .exec(function(error, result){
          if (error) {
            next(error);
          } else {
            next(null, result);
          }
        });
    } else {
      next(null, userServices);
    }
  }

  UserServicesController.subscribe = function(req, res) {
    root.request = req.body;

    if (request.username == req.session.user.username) {

      request.userId = req.session.user.id;

      async.waterfall([
        findOneUserService,
        createUserService,
        updateUserService
      ], function(error, result){
        if (error) {
          res.jsonResponse(400, error);
        } else {
          res.jsonResponse(200, result);
        }
      });
    } else {
      res.jsonResponse(403, 'You can not subscribe with \''+request.username+'\' ');
    }
  }

  module.exports = UserServicesController;
})()